package org.homly.admin.action.product;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.homly.service.SchemeService;
import org.homly.sql.SQLTool;

/**
 * 保存配置和订单
 * @author Dragon
 * @date 2012-11-14
 *
 */
public class SaveProductConfigAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String[] configIds = request.getParameterValues("config_id");
		String[] productIds = request.getParameterValues("product_id");
		String[] configNames = request.getParameterValues("config_name");
		if (configIds.length == productIds.length) {
			// 添加主表
			long shemeId = addShemeMain(request);
			if (shemeId > 0) {
				for (int i = 0; i < configIds.length; i++) {
					String configId = configIds[i];
					String productId = productIds[i];
					String configName = configNames[i];
					if (!productId.equals("")) {
						// 添加明细
						addSchemeDetail(shemeId, configId, productId, configName);
					}
				}
			}
		}
		String type = request.getParameter("type");
		// 保存订单
		if(type != null && type.equals("1")) {
			String sql = "insert into `order`(order_no,order_customer_name,order_customer_mobile,order_customer_qq,order_status,order_create_time)" +
					" values(?,?,?,?,?,?)";
			SQLTool.insert(sql, new Object[]{
					getOrderNo(),
					request.getParameter("scheme_customer_name"),
					request.getParameter("scheme_customer_mobile"),
					request.getParameter("scheme_customer_qq"),
					1,
					new Date()
					});
			sql = "select max(order_id) orderId from `order`";
			List<HashMap<String, String>> list = SQLTool.query(sql);
			if (list != null && list.size() > 0) {
				long orderId = Long.parseLong(list.get(0).get("orderId"));
				for (int i = 0; i < configIds.length; i++) {
					String configId = configIds[i];
					String productId = productIds[i];
					String configName = configNames[i];
					if (!productId.equals("")) {
						// 添加明细
						addOrderDetail(orderId, configId, productId, configName);
					}
				}
			}
		}
		//提示
		PrintWriter pw = response.getWriter();
		pw.append("<script type=\"text/javascript\">");
		if(type != null && type.equals("1")) {
			pw.append("alert(\"购买成功！\");");
		} else {
			pw.append("alert(\"保存方案成功！\");");
		}
//		pw.append("window.location=\"").append(mapping.findForward("success").getPath());
		pw.append("window.history.back();");
		pw.append("</script>");
		pw.flush();

//		return new ActionForward(mapping.findForward("success").getPath(), true);
		return null;
	}
	
	/**
	 * 添加配置表的明细
	 */
	private void addOrderDetail(long orderId, String configId, String productId, String configName) {
		try {
			// 判断是不是其他
			//int isOther = Integer.valueOf(configId) <= -999 ? 1 : 0;
			String sql = "";
			sql = " select * from product where product_status=1 and product_id="
					+ productId;
			List<HashMap<String, String>> list2 = SQLTool.query(sql);
			if (list2 == null || list2.size() == 0)
				return;
			HashMap<String, String> product = list2.get(0);
			sql = "insert into order_detail(order_id,config_id,config_name,product_id,product_brand_name,"
					+ "product_name,product_pic_url,product_price,order_detail_product_num) values(?,?,?,?,?,?,?,?,?)";
			SQLTool.insert(
					sql,
					new Object[] {orderId, configId, configName,
							productId, product.get("product_brand_name"),
							product.get("product_name"),
							product.get("product_pic_url"),
							product.get("product_price"), 1 });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取订单编号
	 * 
	 * @return
	 */
	private String getOrderNo() {
		try {
			String curDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			String resultDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
			String beginTime = curDate + " 00:00:00";
			String endTime = curDate + " 23:59:59";
			String sql = "select (max(order_no) + 1) as orderNo from `order` where order_create_time>='"
					+ beginTime + "' and order_create_time<='" + endTime + "'";
			String schemeNo = "";
			List<HashMap<String, String>> list = SQLTool.query(sql);
			if (list != null && list.size() > 0) {
				schemeNo = list.get(0).get("orderNo");
				if (schemeNo.equals(""))
					schemeNo = resultDate + "0001";
			} else {
				schemeNo = resultDate + "0001";
			}
			return schemeNo;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 添加配置主表
	 * 
	 * @param configId
	 * @param productId
	 */
	private long addShemeMain(HttpServletRequest request) {
		String shemeNo = this.getShemeNo();
		if (shemeNo != null) {
			try {
				String type = request.getParameter("type");
				Short isBuy = (type != null && type.equals("1")) ? ((short) 1) : ((short) 0);
				String customerName = request
						.getParameter("scheme_customer_name");
				String customerMobile = request
						.getParameter("scheme_customer_mobile");
				String customerQq = request.getParameter("scheme_customer_qq");
				int shemeSortNo = SchemeService.getSchemeTopSortNo();
				String sql = "insert into scheme(scheme_no,scheme_is_recommend,scheme_is_buy,"
						+ "scheme_customer_name,scheme_customer_mobile,scheme_customer_qq,scheme_sort_no,"
						+ "scheme_status,scheme_create_time) values(?,?,?,?,?,?,?,?,?)";
				SQLTool.insert(sql,
						new Object[] { shemeNo, 0, isBuy, customerName,
								customerMobile, customerQq, shemeSortNo, 1,
								new Date() });
				sql = "select max(scheme_id) schemeId from scheme";
				List<HashMap<String, String>> list = SQLTool.query(sql);
				if (list != null && list.size() > 0) {
					return Long.parseLong(list.get(0).get("schemeId"));
				} else {
					return 0;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}
		}
		return 0;
	}

	/**
	 * 添加配置表的明细
	 */
	private void addSchemeDetail(long shemeId, String configId, String productId, String configName) {
		try {
			// 判断是不是其他
			int isOther = Integer.valueOf(configId) <= -999 ? 1 : 0;
			String sql = "";
			sql = " select * from product where product_status=1 and product_id="
					+ productId;
			List<HashMap<String, String>> list2 = SQLTool.query(sql);
			if (list2 == null || list2.size() == 0)
				return;
			HashMap<String, String> product = list2.get(0);
			sql = "insert into scheme_detail(scheme_id,scheme_detail_is_other,config_id,config_name,product_id,product_brand_name,"
					+ "product_name,product_pic_url,product_price,scheme_detail_product_num) values(?,?,?,?,?,?,?,?,?,?)";
			SQLTool.insert(
					sql,
					new Object[] { shemeId, isOther, configId, configName,
							productId, product.get("product_brand_name"),
							product.get("product_name"),
							product.get("product_pic_url"),
							product.get("product_price"), 1 });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取配置编号
	 * 
	 * @return
	 */
	private String getShemeNo() {
		try {
			String curDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			String resultDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
			String beginTime = curDate + " 00:00:00";
			String endTime = curDate + " 23:59:59";
			String sql = "select (max(scheme_no) + 1) as schemeNo from scheme where scheme_create_time>='"
					+ beginTime + "' and scheme_create_time<='" + endTime + "'";
			String schemeNo = "";
			List<HashMap<String, String>> list = SQLTool.query(sql);
			if (list != null && list.size() > 0) {
				schemeNo = list.get(0).get("schemeNo");
				if (schemeNo.equals(""))
					schemeNo = resultDate + "0001";
			} else {
				schemeNo = resultDate + "0001";
			}
			return schemeNo;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
